//
//@File    :	10.5_stock10.cpp
//@Time    :	2021/08/26 22:14:08
//@Auther  :	Sun Sheng
//@Contact :	970340843@qq.com
//@Desc    :	Stock class with constructors,destructor added
//

#include <iostream>
#include "10.4_stock10.h"   

//constructors(verbose versions)
Stock::Stock()
{
    std::cout<<"Deafault constructor called\n";
    company="'no name";
    shares=0;
    share_val=0.0;
    total_val=0.0;
}
Stock::Stock(const std::string & co,long n,double pr)
{
    std::cout<<"Constructor using "<<co<<" called\n";
    company=co;

    if (n<0)    
    {
        std::cout<<"number of shares can't be negative; "
                 <<company<<" shares set to 0.\n";
        shares=0;
    }
    else
    {
        shares = n;
    }
    share_val = pr;
    set_tot();
}

//other method
void Stock::buy(long num, double price)
{
    if (num < 0)
    {
        std::cout << "Number of shares purchased can't be negative."
                  << "Transaction is aborted.\n";
    }
    else
    {
        shares += num;
        share_val = price;
        set_tot();
    }
}

void Stock::sell(long num, double price)
{
    using std::cout;
    if (num < 0)
    {
        cout << "Number of shares sold can't be negative."
             << "Transaction is aborted.\n";
    }
    else if (num > shares)
    {
        cout << "You can't sell more than you have!"
             << "Transaction is aborted.\n";
    }
    else
    {
        shares -= num;
        share_val = price;
        set_tot();
    }
}

void Stock::update(double price)
{
    share_val = price;
    set_tot();
}

void Stock::show()
{
    using std::cout;
    using std::ios_base;
    //set format to #.###
    ios_base::fmtflags orig = cout.setf(ios_base::fixed,ios_base::floatfield);
    std::streamsize prec=cout.precision(3);//显示三位小数
    //使用返回值,保证可以恢复到被调用前的状态

    cout << "Company: " << company
         << "  Shares: " << shares << '\n'
         << "  Share Price:$" << share_val;
    //set format to #.##
    cout.precision(2);
    cout<< "  Total Wortj:$" << total_val << '\n';

    //restor original format
    cout.setf(orig,ios_base::floatfield);
    cout.precision(prec);
}